package cn.stylefeng.mferp.modular.business.service.impl;

import cn.stylefeng.mferp.core.common.constant.DatasourceEnum;
import cn.stylefeng.mferp.core.common.constant.factory.ConstantFactory;
import cn.stylefeng.mferp.core.shiro.ShiroKit;
import cn.stylefeng.mferp.core.shiro.ShiroUser;
import cn.stylefeng.mferp.core.util.DateUtil;
import cn.stylefeng.mferp.modular.business.constant.Constants;
import cn.stylefeng.mferp.modular.business.dao.*;
import cn.stylefeng.mferp.modular.business.model.*;
import cn.stylefeng.mferp.modular.business.service.ITrwdService;
import cn.stylefeng.mferp.modular.business.service.ITrwdphbService;
import cn.stylefeng.mferp.modular.business.service.ITrwdphbyclService;
import cn.stylefeng.mferp.modular.system.model.User;
import cn.stylefeng.roses.core.mutidatasource.annotion.DataSource;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.reqres.response.SuccessResponseData;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.ILoggerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.Collator;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;

/**
 * <p>
 * 任务单 服务实现类
 * </p>
 *
 * @author yzr
 * @since 2020-05-27
 */
@Service
public class TrwdServiceImpl extends ServiceImpl<TrwdMapper, Trwd> implements ITrwdService {
    private static final Logger logger = LoggerFactory.getLogger(TrwdServiceImpl.class);

    @Autowired
    private JdbcTemplate sqlServerDispatchJdbcTemplate;
    @Autowired
    private TrwdMapper trwdMapper;
    @Autowired
    private TrwdphbyclMapper trwdphbyclMapper;
    @Autowired
    private TrwdphbMapper trwdphbMapper;
    @Autowired
    private TphbyclMapper tphbyclMapper;
    @Autowired
    private TphbMapper tphbMapper;

    /**
     * 获取任务单列表
     */
    @DataSource(name = DatasourceEnum.DATA_SOURCE_BIZ)
    @Override
    public List<Map<String, Object>> selectTrwds(String beginTime, String endTime, String gcmc,
                                                 String rwdh, String scbt, String zt) {
        return trwdMapper.selectTrwds(beginTime, endTime, gcmc, rwdh, scbt, zt);
    }

    @DataSource(name = DatasourceEnum.DATA_SOURCE_OUT)
    @Override
    public List<Trwd> selectTrwdListOut(String beginTime, String endTime, String zt, String gcmc,
                                        String scbt, String rwdh) {
        return trwdMapper.selectTrwdList(beginTime, endTime, gcmc, rwdh, scbt, zt);
    }

    /**
     * 按任务单号查询
     */
    @DataSource(name = DatasourceEnum.DATA_SOURCE_BIZ)
    @Override
    public Trwd selectByRwdh(String rwdh) {
        return trwdMapper.selectByRwdh(rwdh);
    }

    /**
     * 根据生产拌台查询
     */
    @DataSource(name = DatasourceEnum.DATA_SOURCE_BIZ)
    @Override
    public List<Trwd> selectCheckRwdByScbt(String scbt) {
        return trwdMapper.selectCheckRwdByScbt(scbt);
    }

    /**
     * 调整掺量：添加调整记录、更新配合比信息
     */
    @DataSource(name = DatasourceEnum.DATA_SOURCE_BIZ)
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void adjustCl(Trwd trwd, String scbt, double cl) {
        if(trwd == null || trwd.getFrwdh() == null || StringUtils.isBlank(scbt)) {
            return;
        }
        // 查询原有配方
        List<TrwdphbyclModel> list = trwdphbyclMapper.getTrwdphbYclListByFrwdh(trwd.getFrwdh().toString(), scbt);
        if(list == null || list.isEmpty()) return;
        // 总胶材用量
        BigDecimal pow = BigDecimal.ZERO;
        // 总外加剂用量
        BigDecimal ad = BigDecimal.ZERO;
        // 原有掺量
        BigDecimal ocl;
        // 新掺量
        BigDecimal ncl;
        // fid与sysl的关联
        Map<Integer, BigDecimal> map = new HashMap<>();
        for(TrwdphbyclModel ym : list) {
            Integer id = ym.getFid();
            String ylmc  = ym.getFylmc();
            String pzgg = ym.getFpzgg();
            Double p = ym.getFsysl();
            if((ylmc.contains("水泥") || ylmc.contains("粉煤灰") || ylmc.contains("矿粉")) && p != null) {
                pow = pow.add(new BigDecimal(Double.toString(p)));
            } else if(ylmc.contains("外加剂") && !pzgg.contains("B1") && p != null) {
                ad = ad.add(new BigDecimal(Double.toString(p)));
                map.put(id, new BigDecimal(Double.toString(p)));
            }
        }
        // 总胶材小于等于零，则不更新
        if(pow.compareTo(BigDecimal.ZERO) <= 0) {
            return;
        }
        //百分比
        ocl = ad.multiply(new BigDecimal(100)).divide(pow, 2, RoundingMode.HALF_UP);
        //提高百分比的掺量
        ncl = ocl.add(new BigDecimal(Double.toString(cl)));
        //不能大于5个掺量，不能小于1个掺量
        if(ncl.compareTo(new BigDecimal(5)) > 0 || ncl.compareTo(new BigDecimal(1)) < 0) return;
        for(TrwdphbyclModel ym : list) {
            if(map.containsKey(ym.getFid())) {
                Trwdphbycl trwdphbycl = new Trwdphbycl();
                BigDecimal a = new BigDecimal(Double.toString(ym.getFsysl()));
                trwdphbycl.setFid(ym.getFid());
                //原外加剂A1占原总外加剂 = 现外加剂A1占现总外加剂
                //现外加剂A1 = 原外加剂A1 * 现总外加剂 / 原总外加剂
                //现总外加剂 = 胶凝材料 * 现掺量
                BigDecimal v = pow.multiply(ncl).divide(new BigDecimal(100)).multiply(a).divide(ad, 2, RoundingMode.HALF_UP);
                trwdphbycl.setFsysl(v.doubleValue());
                trwdphbyclMapper.updateById(trwdphbycl);
            }
        }
    }

    /**
     * 添加配合比调整日志
     */
    @DataSource(name = DatasourceEnum.DATA_SOURCE_BIZ)
    @Override
    public boolean addPhbLog(Trwd trwd, String scbt) {
        if(trwd == null || trwd.getFrwdh() == null || StringUtils.isBlank(scbt)) {
            return false;
        }
        List<TrwdphbyclModel> list = trwdphbyclMapper.getTrwdphbYclListByFrwdh(trwd.getFrwdh().toString(), scbt);
        // 日志的备注信息
        StringBuilder bz = new StringBuilder();
        for(TrwdphbyclModel ym : list) {
            String ylmc  = ym.getFylmc();
            String pzgg = ym.getFpzgg();
            Double p = ym.getFsysl();
            bz.append("{").append(ylmc).append("(").append(pzgg).append(")=").append(Double.toString(p)).append("}");
        }
        Trwdphb trwdphb = new Trwdphb();
        trwdphb.setFrwdh(trwd.getFrwdh());
        trwdphb.setFpblx(scbt);
        trwdphb.setFtzsj(DateUtil.getCurrDate());
        trwdphb.setFpbh1(trwd.getFsgpb());
        trwdphb.setFpbh2(trwd.getFsgpb());
        ShiroUser user = ShiroKit.getUser();
        if(user != null && StringUtils.isNotBlank(user.getName())) {
            trwdphb.setFczy(user.getName());
        } else {
            trwdphb.setFczy("管理员");
        }
        trwdphb.setFbz(bz.toString());
        trwdphb.setFljcs(0);
        trwdphb.setFxpbh(0);
        trwdphbMapper.insert(trwdphb);
        return true;
    }

    @DataSource(name = DatasourceEnum.DATA_SOURCE_BIZ)
    @Override
    public boolean addPhbLogForNewSgpb(Trwd trwd, String scbt, String oldSgpb) {
        if(trwd == null || trwd.getFrwdh() == null || StringUtils.isBlank(scbt) || StringUtils.isBlank(oldSgpb)) {
            return false;
        }
        List<TrwdphbyclModel> list = trwdphbyclMapper.getTrwdphbYclListByFrwdh(trwd.getFrwdh().toString(), scbt);
        // 日志的备注信息
        StringBuilder bz = new StringBuilder();
        for(TrwdphbyclModel ym : list) {
            String ylmc  = ym.getFylmc();
            String pzgg = ym.getFpzgg();
            Double p = ym.getFsysl();
            bz.append("{").append(ylmc).append("(").append(pzgg).append(")=").append(Double.toString(p)).append("}");
        }
        Trwdphb trwdphb = new Trwdphb();
        trwdphb.setFrwdh(trwd.getFrwdh());
        trwdphb.setFtzsj(DateUtil.getCurrDate());
        if("0".equals(oldSgpb)) {
            trwdphb.setFpblx("施工");
            trwdphb.setFpbh1(Integer.valueOf(oldSgpb));
        } else {
            trwdphb.setFpblx(scbt);
            trwdphb.setFpbh1(Integer.valueOf(oldSgpb));
        }
        trwdphb.setFpbh2(trwd.getFsgpb());
        ShiroUser user = ShiroKit.getUser();
        if(user != null && StringUtils.isNotBlank(user.getName())) {
            trwdphb.setFczy(user.getName());
        } else {
            trwdphb.setFczy("管理员");
        }
        trwdphb.setFbz(bz.toString());
        trwdphb.setFljcs(0);
        trwdphb.setFxpbh(0);
        trwdphbMapper.insert(trwdphb);
        return true;
    }

    /**
     * 根据任务单号查询
     */
    @DataSource(name = DatasourceEnum.DATA_SOURCE_BIZ)
    @Override
    public List<Trwd> selectCheckRwdByRwdhs(List<String> rwdhs) {
        if(rwdhs == null || rwdhs.isEmpty()) {
            return null;
        }
        /*StringBuilder builder = new StringBuilder();
        for(String rwdh : rwdhs) {
            builder.append("'").append(rwdh).append("',");
        }
        String rwdh = builder.deleteCharAt(builder.length() - 1).toString();*/
        Wrapper<Trwd> wrapper = new EntityWrapper<>();
        wrapper.in("Frwdh", rwdhs);
        return trwdMapper.selectList(wrapper);
    }

    /**
     * 调整砂率：添加调整记录、更新配合比信息
     */
    @DataSource(name = DatasourceEnum.DATA_SOURCE_BIZ)
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void adjustSl(Trwd trwd, String scbt, double sl) {
        if(trwd == null || trwd.getFrwdh() == null || StringUtils.isBlank(scbt)) {
            return;
        }
        // 查询原有配方
        List<TrwdphbyclModel> list = trwdphbyclMapper.getTrwdphbYclListByFrwdh(trwd.getFrwdh().toString(), scbt);
        if(list == null || list.isEmpty()) return;
        // 总骨料用量
        BigDecimal aggregate;
        // 总砂用量
        BigDecimal sand = BigDecimal.ZERO;
        // 总石用量
        BigDecimal stone = BigDecimal.ZERO;
        // 新总砂用量
        BigDecimal sandNew = BigDecimal.ZERO;
        // 新总石用量
        BigDecimal stoneNew = BigDecimal.ZERO;
        // 原有砂率
        BigDecimal osl;
        // 新砂率
        BigDecimal nsl;
        // fid与sysl的关联
        Map<Integer, BigDecimal> map1 = new HashMap<>();
        Map<Integer, BigDecimal> map2 = new HashMap<>();
        for(TrwdphbyclModel ym : list) {
            Integer id = ym.getFid();
            String ylmc  = ym.getFylmc();
            Double p = ym.getFsysl();
            if((ylmc.contains("石") || ylmc.contains("瓜米")) && p != null) {
                stone = stone.add(new BigDecimal(Double.toString(p)));
                map1.put(id, new BigDecimal(Double.toString(p)));
            } else if(ylmc.contains("砂") && p != null) {
                sand = sand.add(new BigDecimal(Double.toString(p)));
                map2.put(id, new BigDecimal(Double.toString(p)));
            }
        }
        // 总骨料小于等于零，则不更新
        aggregate = stone.add(sand);
        if(aggregate.compareTo(BigDecimal.ZERO) <= 0) {
            return;
        }
        osl = sand.multiply(new BigDecimal(100)).divide(aggregate, 1, RoundingMode.HALF_UP);
        nsl = osl.add(new BigDecimal(Double.toString(sl)));
        //不能大于55个砂率，不能小于25个砂率
        if(nsl.compareTo(new BigDecimal(55)) > 0 || nsl.compareTo(new BigDecimal(25)) < 0) return;
        for(TrwdphbyclModel ym : list) {
            //调砂
            if(map2.containsKey(ym.getFid())) {
                Trwdphbycl trwdphbycl = new Trwdphbycl();
                BigDecimal a = new BigDecimal(Double.toString(ym.getFsysl()));
                trwdphbycl.setFid(ym.getFid());
                //原总骨料 = 新总骨料 骨料保持不变、砂占比保持不变
                //砂1/原总砂 = 新砂1/（总骨料*新砂率/100）
                //（总骨料*新砂率/100）*砂1/原总砂 = 新砂1
                BigDecimal v = aggregate.multiply(nsl).divide(new BigDecimal(100)).multiply(a).divide(sand, 3, RoundingMode.UP).divide(new BigDecimal(5), 0, RoundingMode.HALF_UP).multiply(new BigDecimal(5));
                sandNew = sandNew.add(v);
                trwdphbycl.setFsysl(v.doubleValue());
                ym.setFsysl(v.doubleValue());
                trwdphbyclMapper.updateById(trwdphbycl);
            }
            //调石
            if(map1.containsKey(ym.getFid())) {
                Trwdphbycl trwdphbycl = new Trwdphbycl();
                BigDecimal a = new BigDecimal(Double.toString(ym.getFsysl()));
                trwdphbycl.setFid(ym.getFid());
                BigDecimal v = aggregate.multiply(new BigDecimal(100).subtract(nsl)).divide(new BigDecimal(100)).multiply(a).divide(stone, 3, RoundingMode.UP).divide(new BigDecimal(5), 0, RoundingMode.HALF_UP).multiply(new BigDecimal(5));
                trwdphbycl.setFsysl(v.doubleValue());
                ym.setFsysl(v.doubleValue());
                stoneNew = stoneNew.add(v);
                trwdphbyclMapper.updateById(trwdphbycl);
            }
        }
        //扣除差值
        BigDecimal difference = sandNew.add(stoneNew).subtract(aggregate);
        if(difference.compareTo(BigDecimal.ZERO) > 0) {
            for (TrwdphbyclModel ym : list) {
                if (map1.containsKey(ym.getFid())) {
                    Trwdphbycl trwdphbycl = new Trwdphbycl();
                    BigDecimal a = new BigDecimal(Double.toString(ym.getFsysl()));
                    trwdphbycl.setFid(ym.getFid());
                    BigDecimal v = a.subtract(difference);
                    trwdphbycl.setFsysl(v.doubleValue());
                    trwdphbyclMapper.updateById(trwdphbycl);
                    break;
                }
            }
        }
    }

    /**
     * 调整容重：检查容重标准、添加调整记录、更新配合比信息
     */
    @DataSource(name = DatasourceEnum.DATA_SOURCE_BIZ)
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public List<TrwdphbyclModel> adjustRz(Trwd trwd, String scbt, double rzbl) {
        if(trwd == null || trwd.getFrwdh() == null || StringUtils.isBlank(scbt)) {
            return null;
        }
        // 查询原有配方
        List<TrwdphbyclModel> list = trwdphbyclMapper.getTrwdphbYclListByFrwdh(trwd.getFrwdh().toString(), scbt);
        if(list == null || list.isEmpty()) return null;

        // 原有容重
        BigDecimal orz = BigDecimal.ZERO;
        // 新容重
        BigDecimal nrz = BigDecimal.ZERO;
        for(TrwdphbyclModel ym : list) {
            String ylmc  = ym.getFylmc();
            Double p = ym.getFsysl();
            orz = orz.add(new BigDecimal(p));
            if(ylmc.contains("外加剂")) {
                BigDecimal temp = new BigDecimal(p).multiply(new BigDecimal(Double.toString(rzbl))).setScale(2, RoundingMode.HALF_UP);
                nrz = nrz.add(temp);
                ym.setFsysl(temp.doubleValue());
            } else if((ylmc.contains("砂") || ylmc.contains("石") || ylmc.contains("瓜米"))) {
                BigDecimal temp = new BigDecimal(p).multiply(new BigDecimal(Double.toString(rzbl))).setScale(0, RoundingMode.HALF_UP);
                temp = temp.divide(new BigDecimal(5), 0, RoundingMode.HALF_UP).multiply(new BigDecimal(5));
                nrz = nrz.add(temp);
                ym.setFsysl(temp.doubleValue());
            } else {
                BigDecimal temp = new BigDecimal(p).multiply(new BigDecimal(Double.toString(rzbl))).setScale(0, RoundingMode.HALF_UP);
                nrz = nrz.add(temp);
                ym.setFsysl(temp.doubleValue());
            }
        }

        //扣除差值
        orz = orz.multiply(new BigDecimal(Double.toString(rzbl))).setScale(2, RoundingMode.HALF_UP);
        BigDecimal difference = orz.subtract(nrz);
        if(difference.compareTo(BigDecimal.ZERO) != 0) {
            for (TrwdphbyclModel ym : list) {
                String ylmc  = ym.getFylmc();
                Double p = ym.getFsysl();
                if (ylmc.contains("砂")) {
                    BigDecimal a = new BigDecimal(Double.toString(p));
                    BigDecimal v = a.add(difference);
                    v = v.divide(new BigDecimal(5), 0, RoundingMode.HALF_UP).multiply(new BigDecimal(5));
                    ym.setFsysl(v.doubleValue());
                    break;
                }
            }
        }
        logger.info("调整容重 变更后{}", JSON.toJSONString(list));
        return list;
    }

    @DataSource(name = DatasourceEnum.DATA_SOURCE_BIZ)
    @Override
    public void updateTrwdphbycls(List<TrwdphbyclModel> list) {
        for (TrwdphbyclModel ym : list) {
            Trwdphbycl trwdphbycl = new Trwdphbycl();
            trwdphbycl.setFid(ym.getFid());
            trwdphbycl.setFsysl(ym.getFsysl());
            trwdphbyclMapper.updateById(trwdphbycl);
        }
    }

    /**
     * 单个配合比原材料信息保存配方
     */
    @DataSource(name = DatasourceEnum.DATA_SOURCE_BIZ)
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Object saveRecipe(TRecipeModel recipe) {
        String scbt = recipe.getFscbt();
        List<TrwdphbyclModel> list= recipe.getData();
        String rwdh = recipe.getFrwdh();
        String sgpb = recipe.getFsgpb();
        if(!(null != list && list.size() > 0 && StringUtils.isNotBlank(rwdh) &&
                StringUtils.isNotBlank(scbt) && StringUtils.isNotBlank(sgpb))) {
            return new SuccessResponseData(ResponseData.DEFAULT_SUCCESS_CODE, Constants.BUSINESS_TRWD_PARAM_INVALID, null);
        }
        Trwd trwd = trwdMapper.selectByRwdh(rwdh);
        if(trwd == null) {
            return new SuccessResponseData(ResponseData.DEFAULT_SUCCESS_CODE, Constants.BUSINESS_TRWD_RWD_NOT_FOUND, null);
        }

        Tphb tphb = tphbMapper.selectById(Integer.valueOf(sgpb));
        Integer oldFsgpb = trwd.getFsgpb();
        if(tphb != null) {
            // 是否更换施工配比
            boolean flag = false;
            if((oldFsgpb == null && !"0".equals(sgpb)) || (oldFsgpb != null &&
                    oldFsgpb.intValue() != Integer.valueOf(sgpb).intValue())) {
                if (oldFsgpb == null) {
                    oldFsgpb = Integer.valueOf("0");
                }
                trwd.setFsgpb(Integer.valueOf(sgpb));
                trwd.setFphbno(tphb.getFphbno());
                trwdMapper.updateById(trwd);
                flag = true;
            }
            // 删除旧配方，保存新配方，添加调方日志
            trwdphbyclMapper.deleteTrwdphbYclByFrwdhAndScbt(rwdh, scbt);
            for (TrwdphbyclModel ym : list) {
                Trwdphbycl trwdphbycl = new Trwdphbycl();
                trwdphbycl.setFsysl(ym.getFsysl());
                trwdphbycl.setFbtid(Integer.valueOf(scbt));
                trwdphbycl.setFrwdh(Integer.valueOf(rwdh));
                trwdphbycl.setFpzgg(ym.getFpzgg());
                trwdphbycl.setFylmc(ym.getFylmc());
                trwdphbycl.setFpblb(0);
                trwdphbycl.setFplcw(0);
                trwdphbycl.setFhsl(0.0);
                trwdphbycl.setFversion(DateUtil.getCurrentDate());
                trwdphbyclMapper.insert(trwdphbycl);
            }

            // 新增配方日志
            if(flag) {
                addPhbLogForNewSgpb(trwd, scbt, oldFsgpb.toString());
            } else {
                addPhbLog(trwd, scbt);
            }
        }
        return new SuccessResponseData();
    }

    /**
     * 检查容重是否在标准范围内
     * @param list 配方信息
     * @param strength 强度等级 例如C15
     * @return
     */
    @DataSource(name = DatasourceEnum.DATA_SOURCE_GUNS)
    @Override
    public boolean checkBulkDensity(List<TrwdphbyclModel> list, String strength) {
        if(list == null || list.size() <= 0 || StringUtils.isBlank(strength) || !strength.startsWith("C")) {
            return false;
        }
        BigDecimal bulkDensity = BigDecimal.ZERO;
        for (TrwdphbyclModel ym : list) {
            BigDecimal sysl = new BigDecimal(ym.getFsysl());
            bulkDensity = bulkDensity.add(sysl);
        }
        bulkDensity = bulkDensity.setScale(2, RoundingMode.HALF_UP);
        BulkDensityStandard standard = ConstantFactory.me().selectBulkDensityByStrength(strength);
        if(standard == null) {
            return true;
        }
        BigDecimal min = standard.getMinBulkDensity();
        if(min == null) {
            min = BigDecimal.ZERO;
        }
        BigDecimal max = standard.getMaxBulkDensity();
        if(max == null) {
            max = BigDecimal.ZERO;
        }
        return bulkDensity.compareTo(min) >= 0 && bulkDensity.compareTo(max) <= 0;
    }

    /**
     * 获取指定施工配比
     */
    @DataSource(name = DatasourceEnum.DATA_SOURCE_BIZ)
    @Override
    public List<TrwdphbyclModel> getSgpbRecipe(String sgpb) {
        //查询tphb和tphbycl
        List<TrwdphbyclModel> list = tphbyclMapper.getSgpbRecipe(sgpb);
        if(list != null && list.size() > 0) {
            int i = 1;
            for(TrwdphbyclModel model : list) {
                model.setFid(i++);
            }
            list = TrwdphbyclModel.sortByPzgg(list);
        }
        return list;
    }

    /**
     * 调整容重时添加配合比调整日志
     */
    @DataSource(name = DatasourceEnum.DATA_SOURCE_BIZ)
    @Override
    public boolean addPhbLogForAdjustRz(Trwd trwd, String scbt) {
        if(trwd == null || trwd.getFrwdh() == null || StringUtils.isBlank(scbt)) {
            return false;
        }
        List<TrwdphbyclModel> list = trwdphbyclMapper.getTrwdphbYclListByFrwdh(trwd.getFrwdh().toString(), scbt);
        // 日志的备注信息
        StringBuilder bz = new StringBuilder();
        for(TrwdphbyclModel ym : list) {
            String ylmc  = ym.getFylmc();
            String pzgg = ym.getFpzgg();
            Double p = ym.getFsysl();
            bz.append("{").append(ylmc).append("(").append(pzgg).append(")=").append(Double.toString(p)).append("}");
        }
        Trwdphb trwdphb = new Trwdphb();
        trwdphb.setFrwdh(trwd.getFrwdh());
        trwdphb.setFpblx(scbt);
        trwdphb.setFtzsj(DateUtil.getCurrDate());
        trwdphb.setFpbh1(trwd.getFsgpb());
        trwdphb.setFpbh2(trwd.getFsgpb());
        ShiroUser user = ShiroKit.getUser();
        if(user != null && StringUtils.isNotBlank(user.getName())) {
            trwdphb.setFczy(user.getName());
        } else {
            trwdphb.setFczy("管理员");
        }
        trwdphb.setFbz(bz.toString());
        trwdphb.setFljcs(0);
        trwdphb.setFxpbh(0);
        List<Map<String, Object>> list1 = trwdphbMapper.getLastBz(scbt, trwd.getFrwdh().toString());
        if(list1!=null && list1.size()>0) {
            Map<String, Object> map1 = list1.get(0);
            Object lastBz = map1.get("fbz");
            if(lastBz != null) {
                trwdphb.setFbz1(lastBz.toString());
            }
        }
        trwdphbMapper.insert(trwdphb);
        return true;
    }

    /**
     * 调整容重：检查容重标准、添加调整记录、更新配合比信息
     */
    @DataSource(name = DatasourceEnum.DATA_SOURCE_BIZ)
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public boolean rzBack(Trwd trwd, String scbt) {
        if(trwd == null || trwd.getFrwdh() == null || StringUtils.isBlank(scbt)) {
            return false;
        }
        String rwdh = trwd.getFrwdh().toString();
        List<Map<String, Object>> mapList = trwdphbMapper.getLastBz(scbt, rwdh);
        if(mapList!=null && mapList.size()>0) {
            Map<String, Object> map = mapList.get(0);
            Object lastBz = map.get("fbz1");
            if(lastBz != null) {
                String bz = lastBz.toString();
                if(StringUtils.isNotBlank(bz)) {
                    List<TrwdphbyclModel> list = new ArrayList<>();
                    bz = bz.substring(1, bz.length()-1);
                    bz = bz.replaceAll("\\)=", "|");
                    bz = bz.replaceAll("\\(", "|");
                    List<String> temp = Arrays.asList( bz.split("}\\{"));
                    for(String t : temp) {
                        String[] arrayTemp = t.split("\\|");
                        TrwdphbyclModel model = new TrwdphbyclModel();
                        model.setFylmc(arrayTemp[0]);
                        model.setFpzgg(arrayTemp[1]);
                        model.setFsysl(Double.valueOf(arrayTemp[2]));
                        model.setFbtid(Integer.valueOf(scbt));
                        model.setFrwdh(trwd.getFrwdh());
                        model.setFpblb(0);
                        model.setFplcw(0);
                        list.add(model);
                    }
                    if(list != null && list.size() > 1) {
                        list = TrwdphbyclModel.sortByPzgg(list);
                    }

                    // 删除旧配方，保存新配方，添加调方日志
                    trwdphbyclMapper.deleteTrwdphbYclByFrwdhAndScbt(rwdh, scbt);
                    for (TrwdphbyclModel ym : list) {
                        Trwdphbycl trwdphbycl = new Trwdphbycl();
                        trwdphbycl.setFsysl(ym.getFsysl());
                        trwdphbycl.setFbtid(Integer.valueOf(scbt));
                        trwdphbycl.setFrwdh(Integer.valueOf(rwdh));
                        trwdphbycl.setFpzgg(ym.getFpzgg());
                        trwdphbycl.setFylmc(ym.getFylmc());
                        trwdphbycl.setFpblb(0);
                        trwdphbycl.setFplcw(0);
                        trwdphbycl.setFhsl(0.0);
                        trwdphbycl.setFversion(DateUtil.getCurrentDate());
                        trwdphbyclMapper.insert(trwdphbycl);
                    }

                    addPhbLog(trwd, scbt);
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 调砂
     */
    @DataSource(name = DatasourceEnum.DATA_SOURCE_BIZ)
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void adjustSand(Trwd trwd, String scbt, double sand, String sandClass) {
        if(trwd == null || trwd.getFrwdh() == null || StringUtils.isBlank(scbt)) {
            return;
        }
        // 查询原有配方
        List<TrwdphbyclModel> list = trwdphbyclMapper.getTrwdphbYclListByFrwdh(trwd.getFrwdh().toString(), scbt);
        if(list == null || list.isEmpty()) return;
        for(TrwdphbyclModel ym : list) {
            String fylmc = ym.getFylmc();
            Double fsysl = ym.getFsysl();
            if(StringUtils.isNotBlank(fylmc) && sandClass.equals(fylmc)) {
                BigDecimal newVal = new BigDecimal(Double.toString(fsysl)).add(new BigDecimal(Double.valueOf(sand).toString()));
                Trwdphbycl trwdphbycl = new Trwdphbycl();
                trwdphbycl.setFid(ym.getFid());
                trwdphbycl.setFsysl(newVal.doubleValue());
                trwdphbyclMapper.updateById(trwdphbycl);
                break;
            }
        }
    }

    /**
     * 调石
     */
    @DataSource(name = DatasourceEnum.DATA_SOURCE_BIZ)
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void adjustStone(Trwd trwd, String scbt, double stone, String stoneClass) {
        if(trwd == null || trwd.getFrwdh() == null || StringUtils.isBlank(scbt)) {
            return;
        }
        // 查询原有配方
        List<TrwdphbyclModel> list = trwdphbyclMapper.getTrwdphbYclListByFrwdh(trwd.getFrwdh().toString(), scbt);
        if(list == null || list.isEmpty()) return;
        for(TrwdphbyclModel ym : list) {
            String fpzgg = ym.getFpzgg();
            Double fsysl = ym.getFsysl();
            if(StringUtils.isNotBlank(fpzgg) && stoneClass.equals(fpzgg)) {
                BigDecimal newVal = new BigDecimal(Double.toString(fsysl)).add(new BigDecimal(Double.valueOf(stone).toString()));
                Trwdphbycl trwdphbycl = new Trwdphbycl();
                trwdphbycl.setFid(ym.getFid());
                trwdphbycl.setFsysl(newVal.doubleValue());
                trwdphbyclMapper.updateById(trwdphbycl);
                break;
            }
        }
    }

    /**
     * 新增任务单
     */
    @DataSource(name = DatasourceEnum.DATA_SOURCE_BIZ)
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Object saveTrwd(TrwdSaveModel data) {
        Trwd trwd = new Trwd();
        trwd.setFgcmc(data.getFgcmc());
        trwd.setFhtdw(data.getFhtdw());
        trwd.setFjzbw(data.getFjzbw());
        trwd.setFtpz(data.getFtpz());
        trwd.setFjhsl(data.getFjhsl());
        trwd.setFjhrq(data.getFjhrq());
        trwd.setFjzfs(data.getFjzfs());
        trwd.setFgcdz(data.getFgcdz());
        trwd.setFtld(data.getFtld());

        trwd.setFzt("新任务单");
        trwd.setFgls(BigDecimal.ZERO.doubleValue());
        trwd.setFszgg("/");
        trwd.setFscbt("*");
        trwd.setFwcsl(BigDecimal.ZERO.doubleValue());
        trwd.setFczy("接单员");
        trwd.setFsgpb(0);
        trwd.setFljcs(0);
        trwd.setFdlrq(DateUtil.getCurrentDate());
        trwd.setFxpkey(ThreadLocalRandom.current().nextLong(499999999999999999L, 999999999999999999L));
        if (StringUtils.isBlank(data.getZlyq())) {
            data.setZlyq("");
        }
        if (StringUtils.isBlank(data.getGddh())) {
            data.setGddh("");
        }
        // 要过磅（0-5石子)15160003829|/|||||15160003829|||||
        // 备注|渗料规格|外加剂规格|抗渗等级|其他要求|施工单位联系人|工程编号|营销部门联系人|监督号码|优先采用的仓库编号|监控系统工地号|质检员
        // 备注和联系电话
        trwd.setFtbj(new StringBuilder().append(data.getGddh()).append("|/|||||").append(data.getGddh()).append("|||||").toString());

        Integer insert = trwdMapper.insert(trwd);
        if (insert > 0) {
            trwd.setFrwno(String.valueOf(trwd.getFrwdh()));
            trwdMapper.updateById(trwd);
        }

        return new SuccessResponseData();
    }
}
